const frame = document.querySelector('.frame')
const stage1Btn = document.getElementById('stage1-btn')
const endBtn = document.getElementById('end-btn')
const aboutUsBtn = document.getElementById('about-us')
const aboutBtn = document.getElementById('about')
const homeBtn = document.getElementById('home-btn')
const galleryBtn = document.getElementById('gallery-btn')
const menuToggle = document.getElementById('menu-toggle')
const mainMenu = document.querySelector('.main-menu')
const topLine = document.querySelector('.top-line')
const middleLine = document.querySelector('.middle-line')
const bottomLine = document.querySelector('.bottom-line')

const greetCard = document.querySelector('.greet-card')
const stage1Card = document.querySelector('.stage1-card')
const galleryCard = document.querySelector('.gallery-card')
const endCard = document.querySelector('.end-card')

const mus = document.getElementById('mus')
const musControl = document.getElementById('mus-control')
const ions = document.getElementsByClassName('ion')

const audio = new Audio('./Serenity.mp3')

let toggle = 0

const phoneBtn = document.getElementById('phone-btn')
const phoneInp = document.getElementById('phone-input')
const phoneBtnText = document.querySelector('.phone-btn-text')
const phoneBtnBorder = document.querySelector('.phone-btn-border')
const messageWrapper = document.querySelector('.message-wrapper')

audio.volume = 0.1

audio.loop = true

function musicPlay() {
	audio.play()
	if (!audio.paused) {
		for (let i = 0; i < ions.length; i++) {
			ions[i].classList.add('ion-play')
		}
	}
	musControl.addEventListener('click', playerControl)
}

function playerControl() {
	stage1Btn.removeEventListener('click', musicPlay)
	aboutUsBtn.removeEventListener('click', musicPlay)
	if (audio.paused) {
		audio.play()
		for (let i = 0; i < ions.length; i++) {
			ions[i].classList.add('ion-play')
		}
	} else {
		audio.pause()
		for (let i = 0; i < ions.length; i++) {
			ions[i].classList.remove('ion-play')
		}
	}
}

if ('mediaSession' in navigator) {
	navigator.mediaSession.metadata = new MediaMetadata({
		title: 'Чиловая музыка itRoom(😻)',
		artist: 'Kupla',
		artwork: [
			{ src: './photos/4.jpg', sizes: '96x96', type: 'image/png' },
			{ src: './photos/4.jpg', sizes: '128x128', type: 'image/png' },
			{ src: './photos/4.jpg', sizes: '192x192', type: 'image/png' },
			{ src: './photos/4.jpg', sizes: '256x256', type: 'image/png' },
			{ src: './photos/4.jpg', sizes: '384x384', type: 'image/png' },
			{ src: './photos/4.jpg', sizes: '512x512', type: 'image/png' },
		],
	})
}

////////////////////////////////////////////////////////////////////////

stage1Btn.addEventListener('click', () => {
	frame.scrollTop = 0
	greetCard.classList.add('card-remove')
	stage1Card.classList.remove('card-remove')
	galleryCard.classList.add('card-remove')
	endCard.classList.add('card-remove')
	mainMenu.classList.remove('show-menu')
	topLine.classList.remove('top-line-close')
	middleLine.classList.remove('middle-line-close')
	bottomLine.classList.remove('bottom-line-close')

	setTimeout(() => {
		musControl.style.opacity = 1
		musControl.style.cursor = 'pointer'
	}, 2000)
	if (toggle === 0) {
		musicPlay()
		toggle = 1
	}
})

endBtn.addEventListener('click', () => {
	frame.scrollTop = 0
	greetCard.classList.add('card-remove')
	stage1Card.classList.add('card-remove')
	galleryCard.classList.add('card-remove')
	endCard.classList.remove('card-remove')
	mainMenu.classList.remove('show-menu')
	topLine.classList.remove('top-line-close')
	middleLine.classList.remove('middle-line-close')
	bottomLine.classList.remove('bottom-line-close')

	setTimeout(() => {
		phoneInp.style.backgroundColor = 'rgba(146, 255, 103, 0.5)'
		setTimeout(() => {
			phoneInp.style.backgroundColor = '#272727'
		}, 700)
	}, 1000)
})

aboutUsBtn.addEventListener('click', () => {
	frame.scrollTop = 0
	greetCard.classList.add('card-remove')
	stage1Card.classList.add('card-remove')
	galleryCard.classList.add('card-remove')
	endCard.classList.remove('card-remove')
	mainMenu.classList.remove('show-menu')
	topLine.classList.remove('top-line-close')
	middleLine.classList.remove('middle-line-close')
	bottomLine.classList.remove('bottom-line-close')

	setTimeout(() => {
		phoneInp.style.backgroundColor = 'rgba(146, 255, 103, 0.5)'
		setTimeout(() => {
			phoneInp.style.backgroundColor = '#272727'
		}, 700)
	}, 1000)

	setTimeout(() => {
		musControl.style.opacity = 1
		musControl.style.cursor = 'pointer'
	}, 2000)
	if (toggle === 0) {
		musicPlay()
		toggle = 1
	}
})

aboutBtn.addEventListener('click', () => {
	frame.scrollTop = 0
	greetCard.classList.add('card-remove')
	stage1Card.classList.add('card-remove')
	galleryCard.classList.add('card-remove')
	endCard.classList.remove('card-remove')
	mainMenu.classList.remove('show-menu')
	topLine.classList.remove('top-line-close')
	middleLine.classList.remove('middle-line-close')
	bottomLine.classList.remove('bottom-line-close')

	setTimeout(() => {
		phoneInp.style.backgroundColor = 'rgba(146, 255, 103, 0.5)'
		setTimeout(() => {
			phoneInp.style.backgroundColor = '#272727'
		}, 700)
	}, 1000)

	setTimeout(() => {
		musControl.style.opacity = 1
		musControl.style.cursor = 'pointer'
	}, 2000)
	if (toggle === 0) {
		musicPlay()
		toggle = 1
	}
})

homeBtn.addEventListener('click', () => {
	frame.scrollTop = 0
	greetCard.classList.remove('card-remove')
	stage1Card.classList.add('card-remove')
	galleryCard.classList.add('card-remove')
	endCard.classList.add('card-remove')
	mainMenu.classList.remove('show-menu')
	topLine.classList.remove('top-line-close')
	middleLine.classList.remove('middle-line-close')
	bottomLine.classList.remove('bottom-line-close')
})

galleryBtn.addEventListener('click', () => {
	frame.scrollTop = 0
	greetCard.classList.add('card-remove')
	stage1Card.classList.add('card-remove')
	galleryCard.classList.remove('card-remove')
	endCard.classList.add('card-remove')
	mainMenu.classList.remove('show-menu')
	topLine.classList.remove('top-line-close')
	middleLine.classList.remove('middle-line-close')
	bottomLine.classList.remove('bottom-line-close')
	setTimeout(() => {
		musControl.style.opacity = 1
		musControl.style.cursor = 'pointer'
	}, 2000)
	if (toggle === 0) {
		musicPlay()
		toggle = 1
	}
})
////////////////////////////////////////////////////////////

menuToggle.addEventListener('click', () => {
	mainMenu.classList.toggle('show-menu')
	topLine.classList.toggle('top-line-close')
	middleLine.classList.toggle('middle-line-close')
	bottomLine.classList.toggle('bottom-line-close')
})

////////////////////////////////////////////////////////////
const createCanvas = (idName, speed, spritePath) => {
	const canvas = document.getElementById(idName)
	const ctx = canvas.getContext('2d')
	canvas.width = 500
	canvas.height = 500
	const framePerSecond = speed
	let x = 0
	let y = 0
	let counter = 0

	const spriteSheet = new Image()

	spriteSheet.src = spritePath

	const draw = () => {
		ctx.imageSmoothingEnabled = false
		ctx.drawImage(spriteSheet, x, y, 500, 500, 0, 0, 500, 500)

		counter++
		if (framePerSecond === counter) {
			x += 500
			counter = 0
		}

		if (x === spriteSheet.width) {
			x = 0
		}
	}

	const animate = () => {
		ctx.clearRect(0, 0, canvas.width, canvas.height)
		draw()
		requestAnimationFrame(animate)
	}

	animate()
}

createCanvas('cnvCode', 8, './code.webp')

////////////////////////////////////////////////////////////////////////////////////

const canvasBack = document.createElement('canvas')
canvasBack.setAttribute('id', 'cnvBack')
document.body.insertAdjacentElement('beforeend', canvasBack)
canvasBack.oncontextmenu = function (e) {
	e.preventDefault()
}

function polutionDance() {
	var c = document.getElementById('cnvBack')
	var $ = c.getContext('2d')
	var w = (c.width = window.innerWidth)
	var h = (c.height = window.innerHeight)
	var position = [w / 2, h / 2]
	var spacing = 150
	var numw = w / spacing
	var numh = h / spacing

	var draw = function (p) {
		$.fillStyle = '#000'
		$.fillRect(0, 0, w, h)
		$.fillStyle = '#9cffb2'
		$.strokeStyle = '#fd9dff'
		for (var i = 0; i < numh; i++)
			for (var j = 0; j < numw; j++) {
				var diagnalW = j * spacing + (i % 2 ? 0 : spacing / 2)
				var diagnalH = i * spacing
				var arr = [position[0] - diagnalW, position[1] - diagnalH],
					wave = Math.sqrt(arr[0] * arr[0] + arr[1] * arr[1]),
					arr = [arr[0] / wave, arr[1] / wave],
					angle = 50 * (Math.cos(p / 360 - wave / 105) - 1)
				$.beginPath()
				$.arc(
					diagnalW + arr[0] * angle,
					diagnalH + arr[1] * angle,
					2.8,
					0,
					2 * Math.PI,
					false
				)
				$.closePath()
				$.fill()
				for (var n = 0; n < 5; n++) {
					var tail = 50 * (Math.cos((p - 50 * n) / 360 - wave / 105) - 1)
					$.beginPath()
					$.moveTo(diagnalW + arr[0] * angle, diagnalH + arr[1] * angle)
					$.lineWidth = 5 - n
					$.lineTo(diagnalW + arr[0] * tail, diagnalH + arr[1] * tail)
					$.stroke()
				}
			}
	}
	var anim = function (p) {
		window.requestAnimationFrame(anim)
		draw(p)
	}

	anim()
}

if (window.innerWidth >= 420) {
	polutionDance()
} else {
	document.getElementById('cnvBack').remove()
}

window.addEventListener('resize', () => {
	polutionDance()
})

///////////////////////////////////////////////////////////////////

document.addEventListener('DOMContentLoaded', function () {
	var phoneInputs = document.querySelectorAll('input[data-tel-input]')

	var getInputNumbersValue = function (input) {
		// Return stripped input value — just numbers
		return input.value.replace(/\D/g, '')
	}

	var onPhonePaste = function (e) {
		var input = e.target,
			inputNumbersValue = getInputNumbersValue(input)
		var pasted = e.clipboardData || window.clipboardData
		if (pasted) {
			var pastedText = pasted.getData('Text')
			if (/\D/g.test(pastedText)) {
				// Attempt to paste non-numeric symbol — remove all non-numeric symbols,
				// formatting will be in onPhoneInput handler
				input.value = inputNumbersValue
				return
			}
		}
	}

	var onPhoneInput = function (e) {
		var input = e.target,
			inputNumbersValue = getInputNumbersValue(input),
			selectionStart = input.selectionStart,
			formattedInputValue = ''

		if (!inputNumbersValue) {
			return (input.value = '')
		}

		if (input.value.length != selectionStart) {
			// Editing in the middle of input, not last symbol
			if (e.data && /\D/g.test(e.data)) {
				// Attempt to input non-numeric symbol
				input.value = inputNumbersValue
			}
			return
		}

		if (
			['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].indexOf(
				inputNumbersValue[0]
			) > -1
		) {
			if (inputNumbersValue[0] == '9')
				inputNumbersValue = '7' + inputNumbersValue
			var firstSymbols = inputNumbersValue[0] == '8' ? '+7' : '+7'
			formattedInputValue = input.value = firstSymbols + ' '
			if (inputNumbersValue.length > 1) {
				formattedInputValue += '(' + inputNumbersValue.substring(1, 4)
			}
			if (inputNumbersValue.length >= 5) {
				formattedInputValue += ') ' + inputNumbersValue.substring(4, 7)
			}
			if (inputNumbersValue.length >= 8) {
				formattedInputValue += '-' + inputNumbersValue.substring(7, 9)
			}
			if (inputNumbersValue.length >= 10) {
				formattedInputValue += '-' + inputNumbersValue.substring(9, 11)
			}
		} else {
			formattedInputValue = '+' + inputNumbersValue.substring(0, 16)
		}
		input.value = formattedInputValue
		if (phoneInp.value.length == 18) {
			phoneBtnText.classList.add('rainbow-text-1')
			phoneBtnBorder.classList.add('rainbow-border')
			phoneInp.style.backgroundColor = 'rgba(146, 255, 103, 0.5)'
			phoneBtnBorder.style.border = 'none'
			phoneBtn.disabled = false
		} else {
			phoneBtnText.classList.remove('rainbow-text-1')
			phoneBtnBorder.classList.remove('rainbow-border')
			phoneInp.style.backgroundColor = '#272727'
			phoneBtnBorder.style.border = '1px solid #fff'

			phoneBtn.disabled = true
		}
	}
	var onPhoneKeyDown = function (e) {
		// Clear input after remove last symbol
		var inputValue = e.target.value.replace(/\D/g, '')
		if (e.keyCode == 8 && inputValue.length == 1) {
			e.target.value = ''
		}
	}
	for (var phoneInput of phoneInputs) {
		phoneInput.addEventListener('keydown', onPhoneKeyDown)
		phoneInput.addEventListener('input', onPhoneInput, false)
		phoneInput.addEventListener('paste', onPhonePaste, false)
	}
})

const URL_API = `https://itroom.io`

phoneBtn.addEventListener('click', () => {
	const tel = phoneInp
	axios
		.post(URL_API, {
			phone: tel.value,
		})
		.then(() => {
			messageWrapper.style.display = 'flex'
			phoneInp.value = ''
			phoneInp.style.display = 'none'
			phoneBtnBorder.style.display = 'none'
		})
})

let center = [61.246392, 73.419209]

function init() {
	let map = new ymaps.Map('map', {
		center: center,
		zoom: 17,
	})

	let placemark = new ymaps.Placemark(
		center,
		{},
		{
			iconLayout: 'default#image',
			iconImageHref: './placemark.png',
			iconImageOffset: [-19, -44],
		}
	)

	map.controls.remove('geolocationControl') // удаляем геолокацию
	map.controls.remove('searchControl') // удаляем поиск
	map.controls.remove('trafficControl') // удаляем контроль трафика
	map.controls.remove('typeSelector') // удаляем тип
	// map.controls.remove('fullscreenControl') // удаляем кнопку перехода в полноэкранный режим
	map.controls.remove('zoomControl') // удаляем контрол зуммирования
	map.controls.remove('rulerControl') // удаляем контрол правил
	map.behaviors.disable(['scrollZoom']) // отключаем скролл карты (опционально)
	map.width = 100

	map.geoObjects.add(placemark)
}

ymaps.ready(init)
